#include "Cpu.h"
#include "clockMan1.h"
#include "pin_mux.h"
#include <string.h>

#include "bsp_board_driver.h"
#include "bsp_can_driver.h"
#include "bsp_lin_driver.h"
#include "bsp_uart_driver.h"
#include "complex_driver.h"
#include "pwm_driver.h"
#include "user_define.h"
#include "Tps929120.h"


uint8_t volatile timeOutFlag = 0;

void timeOut(uint32_t timeOut)
{
	/* Clear flag */
	timeOutFlag=0;
	/* Set time of timeout */
	LPTMR_DRV_SetCompareValueByUs(INST_LPTMR1, timeOut);

	LPTMR_DRV_StartCounter(INST_LPTMR1);
}

void LPTMR_ISR(void)
{
#if(LPTMR_USED)
	LPTMR_DRV_StopCounter(INST_LPTMR1);
	
    /* Clear compare flag */
    LPTMR_DRV_ClearCompareFlag(INST_LPTMR1);

	timeOutFlag = 1;
#endif
}

void MCU_WDGInit()
{
	WDG_Init(&wdg_pal1_Instance, &wdg_pal1_Config0);
}

void MCU_ClockInit(void)
{
    CLOCK_SYS_Init(g_clockManConfigsArr,   CLOCK_MANAGER_CONFIG_CNT,
                   g_clockManCallbacksArr, CLOCK_MANAGER_CALLBACK_CNT);
    CLOCK_SYS_UpdateConfiguration(0U, CLOCK_MANAGER_POLICY_FORCIBLE);
}

void MCU_GpioInit(void)
{
	PINS_DRV_Init(NUM_OF_CONFIGURED_PINS, g_pin_mux_InitConfigArr);
}

void MCU_PWMInit(void)
{
	PWM_Init(&pwm_pal1Instance, &pwm_pal1Configs);
}

void MCU_LptmrInit(void)
{
#if(LPTMR_USED)
	LPTMR_DRV_Init(INST_LPTMR1, &lpTmr1_config0, false);

    /* Install IRQ handler for LPTMR interrupt */
    INT_SYS_InstallHandler(LPTMR0_IRQn, &LPTMR_ISR, (isr_t *)0);
    /* Enable IRQ for LPTMR */
    INT_SYS_EnableIRQ(LPTMR0_IRQn);
#endif
}

void LPIT0_ISR_Handle()
{
#if(LPIT_USED)
	if(LPIT_DRV_GetInterruptFlagTimerChannels(INST_LPIT1, 1))
	{
		LPIT_DRV_ClearInterruptFlagTimerChannels(INST_LPIT1, 1);
	}
#endif
}

void MCU_LpitInit()
{
#if(LPIT_USED)
    /* Initialize LPIT instance 0
     *  -   Reset and enable peripheral
     */
    LPIT_DRV_Init(INST_LPIT1, &lpit1_InitConfig);
    /* Initialize LPIT channel 0 and configure it as a periodic counter
     * which is used to generate an interrupt every second.
     */
    LPIT_DRV_InitChannel(INST_LPIT1, 0, &lpit1_ChnConfig0);

    /* Install LPIT_ISR as LPIT interrupt handler */
    INT_SYS_InstallHandler(LPIT0_Ch0_IRQn, &LPIT0_ISR_Handle, (isr_t *)0);

	/* Start LPIT0 channel 0 counter */
    LPIT_DRV_StartTimerChannels(INST_LPIT1, (1 << 0));
#endif
}


void MCU_FeedWdg()
{
	WDG_Refresh(&wdg_pal1_Instance);
}

void Board_Init(void)
{
    //Peripheral Initialize
    // MCU_WDGInit();
    MCU_ClockInit();
    MCU_GpioInit();
    Bsp_CAN_Init();
    Bsp_LIN_Init();
    Bsp_UART_Init();
    ADC_Init();
    MCU_LptmrInit();
    MCU_PWMInit();
    // Bsp_IC_Init();
    Bsp_CDD_Init();
    // MCU_FeedWdg();
}
